// pages/compony-pages/compony-media-list/compony-media-list.js
const sizeType = [
    ['compressed'],
    ['original']
];
const uploadFile = require('../../../lib/aliyun/uploadAliyun.js');
const app = getApp();
import Toast from '../../../component/toast/toast';
let imgCoverIndex = -1, videoCoverIndex = -1
Page({

    /**
     * 页面的初始数据
     */
    data: {
        position: 1,
        pageSize: 6,
        pageIndex: -1,
        hasMore: true,
        imgArr: [],
        videoArr: [],
        currentTotal: 0,
        flag: true,
        userInfoId: ''
    },
    // 事件函数
    setCoverClick(e) {
        let index = e.currentTarget.dataset.index;
        let isCover = this.data.position == 1 ? this.data.imgArr[index].IsCover : this.data.videoArr[index].IsCover;
        if(isCover == 1){
            Toast("已是当前封面！");
            return;
        }
        if (this.data.position == 1) {
            //图片
            this.setWorksCover(this.data.imgArr[index].Id, index);
        } else {
            //视频
            this.setWorksCover(this.data.videoArr[index].Id, index);
        }
    },
    longSelectItem(e) {
        if (!this.data.flag) {
            return;
        }
        let index = e.currentTarget.dataset.index;
        let that = this;
        wx.showModal({
            title: '移除作品',
            content: '确认要移除当前作品吗？',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#e71015',
            confirmText: '确认',
            confirmColor: '#333333',
            success: function (res) {
                if (res.confirm) {
                    if (that.data.position == 1) {
                        //图片
                        that.deleteWork(that.data.imgArr[index].Id, index);
                    } else {
                        //视频
                        that.deleteWork(that.data.videoArr[index].Id, index);
                    }
                }
            }
        });
    },
    selectItem(e) {
        let index = e.currentTarget.dataset.index;
        wx.previewImage({
            current: this.data.imgArr[index].MediaUrl,
            urls: [this.data.imgArr[index].MediaUrl]
        })
    },
    clickItem: function (event) {
        let index = event.target.id;
        this.setData({
            position: index,
            hasMore: true,
            pageIndex: -1,
            imgArr: [],
            videoArr: []
        });
        this.getMyWorks(false);
    },
    addRes() {
        let that = this;
        if (this.data.position == 1) {
            wx.chooseImage({
                sizeType: sizeType[0],
                count: 1,
                success(res) {
                    that.localUploadFile(res.tempFilePaths[0]);
                }
            })
        } else {
            wx.chooseVideo({
                sourceType: ['album', 'camera'],
                maxDuration: 60,
                camera: 'back',
                success(res) {
                    that.localUploadFile(res.tempFilePath);
                }
            })
        }
    },
    // 网络请求
    deleteWork(id, index) {
        let that = this;
        wx.showLoading({
            title: '提交中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.deleteEnterpriseMedia,
            data: {
                id: id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    if (that.data.position == 1) {
                        that.data.imgArr.splice(index, 1);
                        that.setData({
                            imgArr: that.data.imgArr
                        });
                    } else {
                        that.data.videoArr.splice(index, 1);
                        that.setData({
                            videoArr: that.data.videoArr
                        });
                    }
                }
                Toast(res.data.Message);
            },
            fail: function (res) {
                console.log("deleteWork fail：" + JSON.stringify(res));
            },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    setWorksCover(id, index) {
        wx.showLoading({
            title: '提交中...',
            mask: true
        })
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.setEnterpriseMedia,
            data: {
                id: id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log(res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let arr = '';
                    let front = `videoArr[0].IsCover`;
                    if (that.data.position == 1) {
                        app.globalData.enterpriseInfo.ImageCover = that.data.imgArr[index].MediaUrl;
                        arr = `imgArr[${index}].IsCover`;
                        if (imgCoverIndex != -1) {
                            front = `imgArr[${imgCoverIndex}].IsCover`;
                            that.setData({
                                [front]: 0
                            });
                        }
                        imgCoverIndex = index;
                    } else {
                        app.globalData.enterpriseInfo.ImageCover = that.data.videoArr[index].MediaUrl;
                        arr = `videoArr[${index}].IsCover`;
                        if (videoCoverIndex != -1) {
                            front = `videoArr[${videoCoverIndex}].IsCover`;
                            that.setData({
                                [front]: 0
                            });
                        }
                        videoCoverIndex = index;
                    }
                    that.setData({
                        [arr]: 1
                    });
                }
                Toast(res.data.Message);
            },
            fail: function (res) {
                console.log("setWorksCover fail:" + JSON.stringify(res));
            },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    localUploadFile(filePath) {
        wx.showLoading({
            title: '上传中...',
            mask: true
        })
        this.uploadSyncFile(filePath).then(res => {
            if (res.statusCode == 200) {
                this.addUserWorks(res.imgUrl);
            }

        }, err => {
            wx.hideLoading();
            Toast("图片上传失败，请检查网络");
            console.log(err);
        });
    },
    addUserWorks(filePath) {
        let that = this;
        let fileType = 0;
        if (this.data.position == 2) {
            fileType = 1;
        }
        wx.request({
            url: app.globalData.serverAddress.addEnterpriseMedia,
            data: {
                Id: "",
                EnterpriseInfoId: app.globalData.enterpriseInfo.Id,
                MediaTitle: "",
                MediaUrl: filePath,
                MediaLength: 0,
                MediaCover: "",
                SortNo: 0,
                MediaType: fileType,
                IsCover: 0
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    // console.log(res.data);
                    that.setData({
                        pageIndex: -1,
                        hasMore: true
                    })
                    that.getMyWorks(true);
                } else {
                    console.log("success：" + JSON.stringify(res.data))
                }
                Toast(res.data.Message);
            },
            fail: function (res) {
                console.log("fail：" + JSON.stringify(res));
            },
            complete: function (res) {
                wx.hideLoading();
            },
        })
    },
    getMyWorks(isAdd) {
        let that = this;
        if (!that.data.hasMore) return;
        wx.showLoading({
            title: '更新数据中...',
            mask: true
        })
        let pageI = ++that.data.pageIndex;
        this.setData({
            pageIndex: pageI
        });
        wx.request({
            url: app.globalData.serverAddress.getEnterpriseMediaList,
            data: {
                pageSize: that.data.pageSize,
                pageIndex: pageI,
                enterpriseId: app.globalData.enterpriseInfo.Id,
                mediaType: that.data.position == 1 ? 0 : 1
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function (res) {
                console.log(res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    console.log(res.data.BodyContent);
                    let list = res.data.BodyContent.List;
                    let count = res.data.BodyContent.TotalCount;
                    let flag = true;
                    let imgs = [];
                    let videos = [];
                    if (isAdd) {
                        flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                        that.setData({
                            imgArr: [],
                            videoArr: [],
                        });
                        list.forEach(function (item) {
                            if (item.MediaType == 0) {
                                imgs.push(item);
                            } else {
                                videos.push(item);
                            }
                        });
                    } else {
                        flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                        imgs = that.data.imgArr;
                        videos = that.data.videoArr;
                        list.forEach(function (item) {
                            if (item.MediaType == 0) {
                                imgs.push(item);
                            } else {
                                videos.push(item);
                            }
                        });
                        imgs.forEach(function (item, index) {
                            if (item.IsCover == 1) {
                                imgCoverIndex = index;
                            }
                        });
                        videos.forEach(function (item, index) {
                            if (item.IsCover == 1) {
                                videoCoverIndex = index;
                            }
                        });
                    }
                    that.setData({
                        imgArr: imgs,
                        videoArr: videos,
                        currentTotal: count,
                        hasMore: flag
                    })
                } else if (res.statusCode == 200 && res.data.CodeStatus == 40005) {
                    that.setData({
                        hasMore: false
                    });
                }else{
                    Toast(res.data.Message);
                }
                
            },
            fail: function (res) {
                console.log("fail" + JSON.stringify(res));
                Toast(res.data.Message);
            },
            complete: function (res) {
                wx.hideLoading();
            },
        })
    },
    uploadSyncFile(path) {
        let promis = new Promise(function (resolve, reject) {
            uploadFile({
                filePath: path,
                dir: 'xianjian_wx_image',
                success: function (res) {
                    resolve(res);
                },
                fail: function (res) {
                    reject(res);
                }
            });
        });
        return promis;
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // let obj = JSON.parse(options.parmas);
        // this.setData({
        //     flag: obj.falg,
        //     userInfoId: obj.userInfoId
        // });
        this.getMyWorks(false);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.getMyWorks(false);
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})